﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using RushTracker.Core.Data;
using RushTracker.Core.Models;
using RushTracker.Core.Util;
using RushTracker.Core.Security;

namespace RushTracker.Web.HttpModules
{
    public class AuthenticationModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            // Nothing here
        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        #endregion

        private void context_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            if (app.Context.User != null && app.Context.User.Identity.IsAuthenticated)
            {

                IDataRepository rep = IoC.Resolve<IDataRepository>();

                User usr = rep.GetObjectById<User>(Convert.ToInt32(app.Context.User.Identity.Name));
                usr.LastActivityDate = DateTime.Now;
                usr.IsAuthenticated = true;

                rep.UpdateObject(usr);
                rep.Flush();

                app.Context.User = new RushTrackerPrincipal(usr);
            }
        }
    }
}
